﻿using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using System.Linq.Dynamic;
using AH.Records.Dto;
using Castle.Core.Logging;
using System;
using AutoMapper;
using System.Collections.Generic;
using Abp.Extensions;

namespace AH.Records
{
    public class ProductAppService : AHAppServiceBase, IProductAppService
    {
        public ILogger Logger { get; set; }

        private readonly IRepository<Product> _productRepository;

        public ProductAppService(IRepository<Product> productRepository)
        {
            _productRepository = productRepository;
            Logger = NullLogger.Instance;
        }

        //public async Task<GetProductOutput> GetProductsAsync(GetProductsInput input)
        //{
        //    var query = _productRepository.GetAll()
        //        .WhereIf(!input.Asin.IsNullOrWhiteSpace(), item => item.Asin.Equals(input.Asin));

        //    return new GetProductOutput
        //    {
        //        Product = Mapper.Map<ProductDto>(await query.FirstOrDefaultAsync())
        //    };
        //}

        public async Task<int>GetProductCount(GetProductCountInput input)
        {
            var count = await _productRepository.GetAll()
               .WhereIf(!input.Asin.IsNullOrWhiteSpace(), item => item.Asin.Equals(input.Asin))
               .CountAsync();

            return count;
        }


        public async Task AddNewProduct(AddNewProductInput input)
        {
            if ((await GetProductCount(new GetProductCountInput {Asin=input.Asin })) == 0)
            {
                await _productRepository.InsertAsync(new Product
                {
                    Asin = input.Asin,
                    Title = input.Title,
                    type = input.type,
                    IsOrder = input.IsOrder
                });
            }
        }


    }
}
